package cn.mengfly.testnrz.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;

/**
 * @author Mengfly
 */
public class ClientUtil {


    public static boolean isNodeExists(CuratorFramework client, String zkPath) {
        try {
            Stat stat = client.checkExists().forPath(zkPath);
            if (null == stat) {
                System.out.println("节点不存在" + zkPath);
                return false;
            } else {
                System.out.println("节点存在" + zkPath);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void createNode(CuratorFramework client, String zkPath, String data) {
        try {
            byte[] payload = "to set content".getBytes(StandardCharsets.UTF_8);
            if (data != null) {
                payload = data.getBytes(StandardCharsets.UTF_8);
            }
            client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(zkPath, payload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteNode(CuratorFramework client, String zkPath) {
        try {
            client.delete().forPath(zkPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
